package client;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

public class LiveFileWriter {
	private static LiveFileWriter instance = null;
	private BufferedWriter out_handle = null;
	private static String newline = System.getProperty("line.separator");
	
	public static LiveFileWriter getInstance() {
		return instance;
	}
	
	public static void Start(String filename) {
		instance = new LiveFileWriter(filename);
	}
	
	public void Finish() {
		try {
			// Close file
			out_handle.close();
		} catch (IOException e) {
			System.err.println("Could not close clients live file: " + e.getMessage());
		}
	}
	
	synchronized public void SerialWrite(String str, ArrayList<String> rows) {
		try {
			// Write to file
			out_handle.write(str + newline);
			for(String s: rows) {		
				out_handle.write(s + newline);		
			}
		} catch (IOException e) {
			System.err.println("Could not write to clients live file: " + e.getMessage());
		}
	}
	
	private LiveFileWriter(String filename) {
		try {
			// Create file 
			FileWriter fstream = new FileWriter(filename);
			out_handle = new BufferedWriter(fstream);
			out_handle.write("Starting to log responses..." + newline);
		} catch (IOException e) {
			System.err.println("Could not create clients live file: " + e.getMessage());
		}
	}
}
